package com.wxdc.nmgyt.nmgytwydc.activity;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AlertDialog;
import android.support.v7.view.ActionMode;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.lcodecore.tkrefreshlayout.utils.LogUtil;
import com.wxdc.nmgyt.nmgytwydc.R;
import com.wxdc.nmgyt.nmgytwydc.adapter.CommitData_RecyclerViewAdapter;
import com.wxdc.nmgyt.nmgytwydc.app.MyApp;
import com.wxdc.nmgyt.nmgytwydc.common.CustomDialog;
import com.wxdc.nmgyt.nmgytwydc.greendao.ope.CbYfInfoBeanDaoOpe;
import com.wxdc.nmgyt.nmgytwydc.greendao.ope.CbYfWzInfoBeanDaoOpe;
import com.wxdc.nmgyt.nmgytwydc.greendao.ope.GmYfInfoBeanDaoOpe;
import com.wxdc.nmgyt.nmgytwydc.greendao.ope.GmYfWzInfoBeanDaoOpe;
import com.wxdc.nmgyt.nmgytwydc.greendao.ope.JcdInfoBeanDaoOpe;
import com.wxdc.nmgyt.nmgytwydc.greendao.ope.PdYfInfoBeanDaoOpe;
import com.wxdc.nmgyt.nmgytwydc.greendao.ope.YdInfoBeanDaoOpe;
import com.wxdc.nmgyt.nmgytwydc.model.CommitDataBean;
import com.wxdc.nmgyt.nmgytwydc.model.GmYfInfoBean;
import com.wxdc.nmgyt.nmgytwydc.model.GmYfWzInfoBean;
import com.wxdc.nmgyt.nmgytwydc.model.JcdInfoBean;
import com.wxdc.nmgyt.nmgytwydc.model.SCommitCbYfInfoBean;
import com.wxdc.nmgyt.nmgytwydc.model.SCommitDataBean;
import com.wxdc.nmgyt.nmgytwydc.model.SCommitYdInfoBean;
import com.wxdc.nmgyt.nmgytwydc.model.YdInfoBean;
import com.wxdc.nmgyt.nmgytwydc.presenter.ToCommitDataPersenter;
import com.wxdc.nmgyt.nmgytwydc.presenter.contract.ToCommitDataContract;
import com.wxdc.nmgyt.nmgytwydc.utils.MyLogUtil;
import com.wxdc.nmgyt.nmgytwydc.utils.Network;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.ResponseBody;

/**
 * Created by Administrator on 2018/5/28.
 */

public class ToCommitDataActivity extends BaseActivity<ToCommitDataPersenter> implements ActionMode.Callback,ToCommitDataContract.View{
    private final String TAG = this.getClass().getSimpleName();
    @BindView(R.id.commit_data_recyclerview)
    RecyclerView mCommitDataRecyclerview;
    @BindView(R.id.bottom_menu)
    LinearLayout mBottomMenu;
    private Context mContext = ToCommitDataActivity.this;
    @BindView(R.id.toolbar_title)
    TextView mToolbarTitle;
    @BindView(R.id.toolbar)
    Toolbar mToolbar;
    private CommitData_RecyclerViewAdapter mViewAdapter;
    //记录Menu的状态
    private boolean isSelectAll;
    //记录选择的Item
    private HashSet<Integer> positionSet;
    public static boolean is_in_actionMode;
    private ActionMode mActionMode;

    @Override
    protected int getLayout() {
        return R.layout.activity_tocommitdata;
    }

    @Override
    protected void initInject() {
        getActivityComponent().Inject(this);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.setSupportActionBar(mToolbar);
        mToolbarTitle.setText(getResources().getString(R.string.manager_01));
        ActionBar actionBar = getSupportActionBar();
        actionBar.setHomeButtonEnabled(true);
        actionBar.setDisplayHomeAsUpEnabled(true);
        actionBar.setTitle("");
        positionSet = new HashSet<>();
        //设置RecyclerView
        mCommitDataRecyclerview.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false));
        list = new ArrayList<>();
        updateDataUI();
        Log.i(TAG, "onCreate: ----------------");
    }

    private List<CommitDataBean> list;

    private void updateDataUI() {
        list.clear();
        List<YdInfoBean> ydInfoBeans = YdInfoBeanDaoOpe.queryAllBackData(mContext, "1",0);
        int ydInfoBeanNums = ydInfoBeans.size();
        for (int i = 0; i < ydInfoBeanNums; i++) {
            CommitDataBean bean = new CommitDataBean();
            bean.setYdInfoBean(ydInfoBeans.get(i));
           /* bean.setCbYfInfoBeanList(CbYfInfoBeanDaoOpe.queryAllForUserIdAndYdmc(mContext, "1", ydInfoBeans.get(i).getSAMPLEPLOTNAME()));
            bean.setGmYfInfoBeanList(GmYfInfoBeanDaoOpe.queryAllForUserIdAndYdmc(mContext,"1",ydInfoBeans.get(i).getSAMPLEPLOTNAME()));
            bean.setPdYfInfoBean(PdYfInfoBeanDaoOpe.queryAllForUserIdAndYdmc(mContext,"1",ydInfoBeans.get(i).getSAMPLEPLOTNAME()));*/
            list.add(bean);
        }
        Log.i(TAG, "updateDataUI: -------------->" + list.size()+"-----"+list.toString());
        if (mViewAdapter == null) {
            mViewAdapter = new CommitData_RecyclerViewAdapter(mContext, list);
            Log.i(TAG, "updateDataUI: ------adapter" + mViewAdapter);
            mCommitDataRecyclerview.setAdapter(mViewAdapter);
            mCommitDataRecyclerview.addItemDecoration(new DividerItemDecoration(mContext, DividerItemDecoration.VERTICAL));//添加默认分割线
            mViewAdapter.setItemClickListener(new CommitData_RecyclerViewAdapter.RecycleViewOnClickListener() {
                @Override
                public void onItemLongClick(View view, int position) {
                    Log.i(TAG, "onItemClick: --------------------" + position);
                    startSupportActionMode(ToCommitDataActivity.this);//打开actionMode
                    list.get(position).isSelect = true;
                    mViewAdapter.notifyDataSetChanged();
                    positionSet.add(position);
                }

                @Override
                public void onImageViewClick(View view, int position) {
                    EventBus.getDefault().postSticky(list.get(position));
                    PhotoActivity.startActivity(mContext);
                }

                @Override
                public void onDoubleClick(View view, int position) {
                    //MyApp.getInstance().showToastLongMessage(mContext, "onDoubleClick----" + list.get(position));
                    /*JcdInfoBean infoBean = JcdInfoBeanDaoOpe.queryForUseridAndYdName(mContext, "1", list.get(position).getYdInfoBean().getSAMPLEPLOTNAME());
                    EventBus.getDefault().postSticky(infoBean);
                    WebActivity.start(mContext, mApp.getHTTPYd(), "ydinfo");*/
                }

                @Override
                public void checkBoxClick(View view, int position) {
                    addOrRemove(position);  //已经有Item被选择,执行添加或删除操作
                }

            });
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int selectId = item.getItemId();
        switch (selectId) {
            case android.R.id.home:
                this.finish();
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    public static void startActivity(Context context) {
        Intent intent = new Intent(context, ToCommitDataActivity.class);
        context.startActivity(intent);
    }

    /**
     * 操作Item记录集合
     */
    private void addOrRemove(int position) {
        if (positionSet.contains(position)) {
            // 如果包含，则撤销选择
            Log.e("----", "remove");
            positionSet.remove(position);
        } else {
            // 如果不包含，则添加
            Log.e("----", "add");
            positionSet.add(position);
        }
        if (positionSet.size() == 0) {
            mActionMode.finish();
        }

    }

    /*
    * 删除选中项
    * */
    private void deleteSelectItems() {
        HashSet<CommitDataBean> valueSet = new HashSet<>();
        for (Integer integer : positionSet) {
            valueSet.add(mViewAdapter.getItem(integer));
        }
        for (CommitDataBean itemModel : valueSet) {
            //删除草本分种样方
            int cbYfLen = itemModel.getCbYfInfoBeanList().size();
            for (int i = 0 ; i < cbYfLen; i++) {
                CbYfWzInfoBeanDaoOpe.deleteInTx(mContext,CbYfWzInfoBeanDaoOpe.queryAllForCbyfId(mContext,itemModel.getCbYfInfoBeanList().get(i).getId()));
            }
            CbYfInfoBeanDaoOpe.deleteInTx(mContext,itemModel.getCbYfInfoBeanList());
            //删除灌木分种样方
            int gmYfLen = itemModel.getGmYfInfoBeanList().size();
            for (int i= 0; i < gmYfLen; i++) {
                GmYfWzInfoBeanDaoOpe.deleteInTx(mContext,GmYfWzInfoBeanDaoOpe.queryAllForCbyfId(mContext,itemModel.getGmYfInfoBeanList().get(i).getId()));
            }
            GmYfInfoBeanDaoOpe.deleteInTx(mContext,itemModel.getGmYfInfoBeanList());
            //删除样地信息表
            YdInfoBeanDaoOpe.deleteData(mContext,itemModel.getYdInfoBean());
            mViewAdapter.remove(itemModel);
        }
        mViewAdapter.notifyDataSetChanged();
        positionSet.clear();
    }

    /*全选或取消全选
    * */
    private void selectAll() {
        int len = list.size();
        if (!isSelectAll) {
            isSelectAll = true;
            for (int i = 0; i < len; i++) {
                list.get(i).isSelect = true;
                positionSet.add(i);
            }
            mViewAdapter.notifyDataSetChanged();
        } else {
            isSelectAll = false;
            for (int i = 0; i < len; i++) {
                list.get(i).isSelect = false;
                positionSet.remove(i);
            }
            mViewAdapter.notifyDataSetChanged();
        }
    }

    //==========================================================================
    @Override
    public boolean onCreateActionMode(ActionMode mode, Menu menu) {
        if (mActionMode == null) {
            mActionMode = mode;

        }
        mActionMode.setTitle(getResources().getString(R.string.manager_01));
        getMenuInflater().inflate(R.menu.commitdata_actionmode, menu);
        is_in_actionMode = true;
        return true;
    }

    @Override
    public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
        return false;
    }
    private AlertDialog commitDialog;
    @Override
    public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
        switch (item.getItemId()) {
            case R.id.actionmode_select_all:
                selectAll();
                break;
            case R.id.actionmode_delete:
                if (positionSet.size() <= 0) {
                    MyApp.getInstance().showToastLongMessage(mContext,"未选中数据");
                    return false;
                }
                deleteSelectItems();
                break;
            case R.id.actionmode_done:
                if (positionSet.size() <= 0) {
                    MyApp.getInstance().showToastLongMessage(mContext,"未选中数据");
                    return false;
                }
                Log.i(TAG, "onActionItemClicked: ---------提交选中数据");
                if (!Network.isConnected(mContext)) {
                    mApp.showToastLongMessage(mContext,getResources().getString(R.string.no_network));
                    return false;
                }
                if (commitDialog == null) {
                    commitDialog = new AlertDialog.Builder(mContext)
                            .setMessage("是否上传数据?")
                            .setNegativeButton("否", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    if (commitDialog != null) {
                                        commitDialog.dismiss();
                                    }
                                }
                            })
                            .setPositiveButton("是", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    if (commitDialog != null) {
                                        commitDialog.dismiss();
                                    }
                                    commitDataToServices();
                                }
                            })
                            .create();
                }
                commitDialog.show();
                break;
        }
        return false;
    }

    @Override
    public void onDestroyActionMode(ActionMode mode) {
        mode.finish();
        is_in_actionMode = false;
        Log.i(TAG, "onDestroyActionMode: ----start---" + System.currentTimeMillis());
        for (CommitDataBean obj : list) {
            if (obj.isSelect) {
                obj.isSelect = false;
            }
        }
        Log.i(TAG, "onDestroyActionMode: ----end---" + System.currentTimeMillis());
        positionSet.clear();
        mViewAdapter.notifyDataSetChanged();
    }

    /*
    * 提交选中数据到服务器
    * */
    private CustomDialog mCustomDialog;
    private void commitDataToServices(){
        List<SCommitDataBean> commitDataBeanList = new ArrayList<>();
        //使用iterator()对集合遍历
        Iterator<Integer> it = positionSet.iterator();
        Log.i(TAG, "commitDataToServices: ---------pisitionSet-->"+positionSet.size());
        while (it.hasNext()) {
            CommitDataBean commitDataBean = list.get(it.next());
            //样地
            SCommitDataBean dataBean = new SCommitDataBean();
            SCommitYdInfoBean ydInfoBean = new SCommitYdInfoBean();
            ydInfoBean.setBean(commitDataBean.getYdInfoBean());
            ydInfoBean.setIMGPATH(commitDataBean.getYdInfoBean().getIMGPATH());
            dataBean.setYdInfoBean(ydInfoBean);
           /* if (dataBean.getYdInfoBean().getIMGPATH()!= null && !dataBean.getYdInfoBean().getIMGPATH().isEmpty() && dataBean.getYdInfoBean().getBean().getISUPLOADPIC() == 0) {
                Log.i(TAG, "commitDataToServices: -----yd-------"+dataBean.getYdInfoBean().getBean().getISUPLOADPIC());
                mApp.showToastLongMessage(mContext,"请先上传图片再提交数据");
                return;
            }*/
            //草本样方
            int len = commitDataBean.getCbYfInfoBeanList().size();
            List<SCommitCbYfInfoBean> sCommitCbYfInfoBeans = new ArrayList<>();
            for (int i = 0 ; i < len ; i++) {
               /* if (commitDataBean.getCbYfInfoBeanList().get(i).getIMGPATH() != null && !commitDataBean.getCbYfInfoBeanList().get(i).getIMGPATH().isEmpty() && commitDataBean.getCbYfInfoBeanList().get(i).getISUPLOADPIC() == 0 ) {
                    Log.i(TAG, "commitDataToServices: -----cb-------"+commitDataBean.getCbYfInfoBeanList().get(i).getISUPLOADPIC());
                    mApp.showToastLongMessage(mContext,"请先上传图片再提交数据");
                    return;
                }*/
                SCommitCbYfInfoBean sCommitCbYfInfoBean = new SCommitCbYfInfoBean();
                sCommitCbYfInfoBean.setGrassBean(commitDataBean.getCbYfInfoBeanList().get(i));
                //sCommitCbYfInfoBean.setIMGPATH(commitDataBean.getCbYfInfoBeanList().get(i).getIMGPATH());
                //sCommitCbYfInfoBean.setWzInfos(commitDataBean.getCbYfInfoBeanList().get(i).getWzInfos());
                sCommitCbYfInfoBeans.add(sCommitCbYfInfoBean);
            }
            dataBean.setCbYfInfoBeanList(sCommitCbYfInfoBeans);
            //灌木样方
            dataBean.setGmYfInfoBeanList(commitDataBean.getGmYfInfoBeanList());
            Log.i(TAG, "commitDataToServices: ----------dddddddd---------->"+commitDataBean.getGmYfInfoBeanList());
            Log.i(TAG, "commitDataToServices: --------------before---->"+dataBean.getGmYfInfoBeanList());
            for (GmYfInfoBean obj : dataBean.getGmYfInfoBeanList()) { // 疑问？ 添加这段代码后台可以接收wzInfos数据
                //obj.getWzInfos();
                Log.i(TAG, "commitDataToServices: --------------before111111---->");
            }
            Log.i(TAG, "commitDataToServices: ----------after---->"+dataBean.getGmYfInfoBeanList());
            //频度样方
            dataBean.setPdYfInfoBean(commitDataBean.getPdYfInfoBean());
            //
            commitDataBeanList.add(dataBean);
        }
        if (mCustomDialog == null) {
            mCustomDialog = new CustomDialog(mContext, "数据上传中...");
        }
        mCustomDialog.showDialog();
        Log.i(TAG, "commitDataToServices: ---------"+commitDataBeanList.size()+"------->"+commitDataBeanList.toString());
        MyLogUtil.i("test-------",commitDataBeanList.toString());
       /* for (int i = 0 ; i < commitDataBeanList.size(); i++) {
            Log.i(TAG, "commitDataToServices: ------------>"+commitDataBeanList.get(i).toString());
        }*/
        mPersenter.DataUpload(commitDataBeanList,"1","2");
        //mCustomDialog.hideDialog();
    }
    //数据上传完成返回函数
    @Override
    public void DataUploadOkBackResult(ResponseBody responseBody) {
        Log.i(TAG, "DataUploadOkBackResult: -----------数据上传完成");
        mApp.showToastLongMessage(mContext,"上传完成");
        mCustomDialog.hideDialog();
        //deleteSelectItems();
    }
    @Override
    public void showError(String msg) {
        mApp.showToastLongMessage(this, msg);
        if (mCustomDialog != null) {
            mCustomDialog.hideDialog();
        }
    }
    //=================================================================================

    @Override
    protected void onResume() {
        super.onResume();
        if (mViewAdapter != null) {
            mViewAdapter.notifyDataSetChanged();
            Log.i(TAG, "onResume: ----------------------");
        }
    }

}
